import matplotlib.pyplot as plt
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import *
import sys
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

class Demo(FigureCanvas):

    selectSignal = pyqtSignal(int, float)

    def __init__(self, parent=None, width=5, height=4, dpi=100):

        plt.rcParams['font.family'] = ['SimHei']
        plt.rcParams['axes.unicode_minus'] = False
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)

        self.axes2 = self.fig.add_subplot(111)
        self.axes2.minorticks_on()
        self.axes2.set_ylabel('扭矩(N·m)')
        self.axes2.set_xlabel('时间(s)')
        self.axes2.set_xlim((0, 15))
        self.axes2.set_ylim((0, 100))

        self.axes = self.axes2.twinx()
        self.axes.minorticks_on()
        self.axes.set_ylabel('温度(N·m)')
        self.axes.set_xlabel('时间(s)')
        self.axes.set_ylim((0, 300))

        self.vline_a = self.axes.axvline(2, ls='--', c='r', lw=2)
        self.vline_b = self.axes.axvline(4, ls='--', c='g', lw=2)
        self.vline_x = self.axes.axvline(6, ls='--', c='b', lw=2)
        self.vline_g = self.axes.axvline(8, ls='--', c='k', lw=2)
        self.vline_e = self.axes.axvline(10, ls='--', c='y', lw=2)

        self.vlines = [self.vline_a, self.vline_b, self.vline_x, self.vline_g, self.vline_e]
        self.select = None
        self.selectidx = None


        # self.connect()
        self.show()


    def updateAxes(self):
        """每次画图时，先调用这个函数更新图像"""
        self.axes2.clear()
        self.axes.clear()
        self.axes2.minorticks_on()
        self.axes2.set_ylabel('扭矩(N·m)')
        self.axes2.set_xlabel('时间(s)')
        self.axes.minorticks_on()
        self.axes.set_ylabel('温度(N·m)')
        self.axes.set_xlabel('时间(s)')
        for vline in self.vlines:
            self.axes.add_line(vline)
        self.select = None
        self.selectidx = None

    def myContains(self, event):
        """判断选中的对象是否为这几条垂直线"""
        for idx, vline in enumerate(self.vlines):
            contains, attrd = vline.contains(event)
            if contains:
                self.select = vline
                self.selectidx = idx
                return True

        return False

    def connect(self):
        'connect to all the events we need'
        self.cidpress = self.mpl_connect('button_press_event', self.on_press)
        self.cidrelease = self.mpl_connect('button_release_event', self.on_release)
        self.cidmotion = self.mpl_connect('motion_notify_event', self.on_motion)

    def on_press(self, event):

        if event.inaxes != self.axes:
            return
        if not self.myContains(event):
            return
        self.select.set_animated(True)

        self.draw()
        self.background = self.copy_from_bbox(self.axes.bbox)

        # now redraw just the rectangle
        self.axes.draw_artist(self.select)

        # and blit just the redrawn area
        self.blit(self.axes.bbox)

    def on_motion(self, event):
        if event.inaxes != self.axes:
            return
        if not self.select:
            return
        # 更新选中直线的x坐标
        self.select.set_xdata(event.xdata)
        # 这个信号用于实时传送垂直线划过时的x坐标
        self.selectSignal.emit(self.selectidx, event.xdata)
        self.restore_region(self.background)
        self.axes.draw_artist(self.select)
        self.blit(self.axes.bbox)

    def on_release(self, event):
        if not self.select:
            return

        self.select.set_animated(False)
        self.background = None
        self.select = None
        self.draw()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()




    sys.exit(app.exec_())
